package com.hust360.percent.activity;

import java.io.Serializable;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.view.animation.LayoutAnimationController;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.TableLayout;
import android.widget.TextView;

import com.hust360.percent.PercentApplication;
import com.hust360.percent.R;
import com.hust360.percent.adapter.StoreListAdapter;
import com.hust360.percent.pojo.Discount;
import com.hust360.percent.pojo.DiscountLocal;
import com.hust360.percent.pojo.Shop;
import com.hust360.percent.pojo.ShopLocal;
import com.hust360.percent.pojo.SortInterfaceImpls;
//import com.hust360.percent.pojo.SortInterfaceImpls.SortByLikeImpl;
import com.hust360.percent.utils.ActivityUtils;
import com.hust360.percent.utils.DisplayUtils;
import com.hust360.percent.view.PopupMenuPane;
import com.hust360.percent.view.SearchPane;

public class BoutiqueActivity extends Activity {

	/**
	 * 程序的实例
	 */
	PercentApplication application;

	/**
	 * TAG FOR DDMS LOGCAT
	 */
	public static final String TAG = "BoutiqueActivity";

	/**
	 * 显示精品的ListView
	 */
	ListView boutiqueListView;
	/**
	 * boutiqueListView的适配器
	 */
	private StoreListAdapter adapter;

	/**
	 * 排序方式按钮
	 */
	TextView sortBtn;

	/**
	 * 全部、购物、美食等类编选择按钮
	 */
	TextView typesBtn;

	/**
	 * 标题栏上的选择地点的按钮
	 */
	TextView areaBtn;

	/**
	 * 标题栏上的搜索按钮
	 */
	ImageButton searchBtn;

	/**
	 * 搜索面板的根 (root)
	 */
	SearchPane search_pane;
	/**
	 * 搜索面板中关键字的输入框
	 */
	EditText keywordEditText;

	/**
	 * 搜索面板中的搜索按钮
	 */
	ImageButton doSearchBtn;
	LayoutInflater inflater;

	/**
	 * BoutiqueActivity的ContentView的根
	 */
	LinearLayout root;

	/**
	 * 搜索面板的半透明的下半部分，点击可以隐藏搜索面板
	 */
	View rmSearchPane;

	/**
	 * 用来操控搜索面板显示或者隐藏的窗口管理器
	 */
	WindowManager manager;

	/**
	 * 类别选择菜单面板
	 */
	PopupMenuPane typePopupMenuPane;

	/**
	 * 类别面板窗口(含透明部分)
	 */
	LinearLayout typeWindow;

	/*-----------------------------排序选择菜单面板相关----------------------------*/
	/**
	 * 排序选择菜单面板
	 */
	PopupMenuPane sortPopupMenuPane;

	/**
	 * 默认排序按钮
	 */
	TextView sortDefaultBtn;

	/**
	 * 人气最高排序按钮
	 */
	TextView sortFavoriteBtn;

	/**
	 * 折扣最大按钮
	 */
	TextView sortDiscountBtn;

	/**
	 * 最新活动排序按钮
	 */
	TextView sortLatestBtn;

	/**
	 * 距离排序按钮
	 */
	TextView sortDistanceBtn;

	/**
	 * 排序监听器
	 */
	SortPaneBtnsListener sortPaneBtnsListener;

	/**
	 * boutique activity界面出去标题的布局的跟
	 */
	FrameLayout listframe;

	/*---------------------------多线程相关的--------------------------------*/
	/**
	 * 
	 */
	static Handler handler;

	private static final int MESSAGE_DATA_PREPARED = 1;

	/**
	 * 
	 */
	HandlerThread thread;

	/**
	 * 
	 */
	BoutiqueSortRunnable sortRunnable;

	/* ---------------------------数据相关------------------ */
	/**
	 * 精品选项卡里面存放的打折信息的List
	 */
	List<Discount> list;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState); // 调用父类的onCreate();
		ActivityUtils.addActivity(BoutiqueActivity.this);
		setContentView(R.layout.activity_boutique);

		application = (PercentApplication) getApplication();

		// 初始界面
		init();
		initTypePane();
		initSortPane();

		// 初始化多线程对象
		initThread();

		// 初始化ListView的数据
		initData();
		handler.post(new Runnable() {
			@Override
			public void run() {
			}
		});
	}

	private void init() {

		boutiqueListView = (ListView) findViewById(R.boutique_activity.listview);
		adapter = new StoreListAdapter(this);
		adapter.setList(list);
		adapter.setListView(boutiqueListView);
		boutiqueListView.setAdapter(adapter);
		boutiqueListView.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				sortPopupMenuPane.hide();
				typePopupMenuPane.hide();
				return false;
			}
		});
		boutiqueListView.setOnItemClickListener(new BtqItemClickListener());
		root = (LinearLayout) findViewById(R.id.boutique_root);
		root.setOnTouchListener(new View.OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				typePopupMenuPane.hide();
				sortPopupMenuPane.hide();
				return false;
			}
		});
		sortBtn = (TextView) findViewById(R.boutique_activity.sort_btn);
		typesBtn = (TextView) findViewById(R.boutique_activity.type_btn);
		areaBtn = (TextView) findViewById(R.boutique_activity.area_btn);
		areaBtn.setText(application.getCurCity().name);
		areaBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(BoutiqueActivity.this,
						CityActivity.class);
				intent.putExtra(TAG, BoutiqueActivity.TAG);
				intent.putExtra("city", areaBtn.getText());
				startActivityForResult(intent, 1);
			}
		});

		searchBtn = (ImageButton) findViewById(R.boutique_activity.search_btn);
		searchBtn.setOnClickListener(new SearchBtnListener());
		inflater = (LayoutInflater) getParent().getSystemService(
				Context.LAYOUT_INFLATER_SERVICE);
		search_pane = (SearchPane) inflater.inflate(R.layout.search_pane, null);

		rmSearchPane = search_pane.findViewById(R.search_pane.transparent_area);
		rmSearchPane.setOnClickListener(new RmSearchPaneListener());
		manager = (WindowManager) getParent().getSystemService(
				Context.WINDOW_SERVICE);
		doSearchBtn = (ImageButton) search_pane
				.findViewById(R.search_pane.search_btn);
		keywordEditText = (EditText) search_pane
				.findViewById(R.search_pane.editText);
		keywordEditText.setOnKeyListener(new SearchPaneKeyListener());
		typesBtn.setOnClickListener(new TypeBtnListener());
		sortBtn.setOnClickListener(new SortBtnListener());

		listframe = (FrameLayout) findViewById(R.boutique_activity.frame);

		/*
		 * 设置搜索面板出现的动画效果
		 */
		TranslateAnimation animation = new TranslateAnimation(0, 0, -800, 0);
		animation.setDuration(300l);
		search_pane
				.setLayoutAnimation(new LayoutAnimationController(animation));
	}

	/**
	 * 初始化类别菜单的界面
	 */

	private void initTypePane() {

		Log.e(TAG, "initTypePane() called!");
		typePopupMenuPane = new PopupMenuPane(this);
		LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT);
		FrameLayout.LayoutParams params2 = new FrameLayout.LayoutParams(
				FrameLayout.LayoutParams.WRAP_CONTENT,
				FrameLayout.LayoutParams.WRAP_CONTENT);
		typePopupMenuPane.addView(
				getLayoutInflater().inflate(R.layout.type_menu_pane, null),
				params);
		typePopupMenuPane.setVisibility(View.INVISIBLE);
		listframe.addView(typePopupMenuPane, 0);
		typePopupMenuPane.setLayoutParams(params2);
		typePopupMenuPane.bringToFront();
	}

	/**
	 * 初始化排序选择菜单
	 */

	private void initSortPane() {
		sortPopupMenuPane = new PopupMenuPane(this);
		LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT);
		FrameLayout.LayoutParams params2 = new FrameLayout.LayoutParams(
				FrameLayout.LayoutParams.WRAP_CONTENT,
				FrameLayout.LayoutParams.WRAP_CONTENT);
		TableLayout btnTable = (TableLayout) getLayoutInflater().inflate(
				R.layout.sort_menu_pane, null);
		sortPopupMenuPane.addView(btnTable, params);
		sortPopupMenuPane.setVisibility(View.INVISIBLE);
		listframe.addView(sortPopupMenuPane, 0);
		sortPopupMenuPane.setLayoutParams(params2);
		params2.gravity = Gravity.RIGHT | Gravity.TOP;
		sortPopupMenuPane.bringToFront();

		sortDefaultBtn = (TextView) btnTable
				.findViewById(R.sort_menu_pane.default_order);
		sortDiscountBtn = (TextView) btnTable
				.findViewById(R.sort_menu_pane.best_discount);
		sortDistanceBtn = (TextView) btnTable
				.findViewById(R.sort_menu_pane.nearest);
		sortFavoriteBtn = (TextView) btnTable
				.findViewById(R.sort_menu_pane.most_popular);
		sortLatestBtn = (TextView) btnTable
				.findViewById(R.sort_menu_pane.latest_info);
		sortPaneBtnsListener = new SortPaneBtnsListener();
		sortDefaultBtn.setOnClickListener(sortPaneBtnsListener);
		sortDiscountBtn.setOnClickListener(sortPaneBtnsListener);
		sortDistanceBtn.setOnClickListener(sortPaneBtnsListener);
		sortFavoriteBtn.setOnClickListener(sortPaneBtnsListener);
		sortLatestBtn.setOnClickListener(sortPaneBtnsListener);
	}

	/**
	 * 初始化自己所要的数据
	 */
	private synchronized void initData() {
		list = new ArrayList<Discount>();
		Shop shop = null;
		Map<String, String> map = new HashMap<String, String>();
		map.put(Shop.CITY_ID, application.getCurCity().id + "");
		List<Shop> shopList = application.getShopDao().findWithMap(map);
		Iterator<Shop> iterator = shopList.iterator();
		while (iterator.hasNext()) {
			shop = iterator.next();
			list.addAll(shop.getDiscountInfos());
		}
		adapter.setList(list);
	}

	/**
	 * 重新加载数据,仅仅更新数据
	 */
	private void reloadData() {

		List<Discount> newList = new ArrayList<Discount>();
		Shop shop = new ShopLocal();
		Discount info = new DiscountLocal();

		Map<String, String> map = new HashMap<String, String>();
		map.put(Shop.CITY_ID, application.getCurCity().id + "");
		List<Shop> shopList = application.getShopDao().findWithMap(map);// findByArgs(null,
		// Shop.CITY_ID + "='" + application.getCurCity().id + "'", null,
		// null, null, null);
		Log.i(TAG, shopList.size() + " is the lenght of list");

		Iterator<Shop> iterator = shopList.iterator();
		map.clear();
		while (iterator.hasNext()) {
			shop = iterator.next();
			info.shopid = shop.id;
			map.put(Discount.SHOP_ID, shop.id + "");
			newList.addAll(application.getDiscountInfoDAO().findWithMap(map));
			map.clear();
			// .findByArgs(
			// null,
			// Discount.SHOP_ID_COLUMN + "='"
			// + shop.getShopId() + "'", null, null, null,
			// null));
		}

		Log.i(TAG, newList.size() + "length of discountinfo list ");

		synchronized (list) {
			list = newList;
			adapter.setList(newList);
		}
	}

	/**
	 * 初始化多线程
	 */
	private void initThread() {
		thread = new HandlerThread("thread_to_sort_or_connect_internet");
		thread.start();
		handler = new BoutiqueHandler(this, thread.getLooper());
		sortRunnable = new BoutiqueSortRunnable();
		sortRunnable.order = BoutiqueSortRunnable.ORDER_DEFAULT;
	}

	/**
	 * 标题栏上搜索按钮的监听器
	 * 
	 * @author yangyang
	 * 
	 */
	private class SearchBtnListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			WindowManager.LayoutParams params = new WindowManager.LayoutParams();
			params.height = WindowManager.LayoutParams.MATCH_PARENT;
			params.width = WindowManager.LayoutParams.MATCH_PARENT;
			params.type = WindowManager.LayoutParams.TYPE_APPLICATION;
			params.format = PixelFormat.RGBA_8888;
			if (search_pane.getParent() != null) {
				manager.removeView(search_pane);
			} else {
				manager.addView(search_pane, params);
				search_pane.startLayoutAnimation();
			}
		}

	}

	/**
	 * 搜索面板中半透明区域的点击监听器，点击隐藏搜索面板
	 * 
	 * @author yangyang
	 */
	private class RmSearchPaneListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if (search_pane.getParent() != null) {
				manager.removeView(search_pane);
			}
		}

	}

	/**
	 * 搜索面板中关键字输入框的按键监听器，按返回键触发搜索面板隐藏事件
	 * 
	 * @author yangyang
	 */
	private class SearchPaneKeyListener implements View.OnKeyListener {

		@Override
		public boolean onKey(View v, int keyCode, KeyEvent event) {
			// TODO Auto-generated method stub
			Log.e(getClass().getSimpleName(), "OnKeyListener");
			if (keyCode == KeyEvent.KEYCODE_BACK
					&& search_pane.getParent() != null) {
				manager.removeView(search_pane);
			}
			return false;
		}
	}

	/**
	 * 类别按钮的监听器
	 */
	private class TypeBtnListener implements View.OnClickListener {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			sortPopupMenuPane.hide();
			int[] locate = new int[2];
			typesBtn.getLocationOnScreen(locate);
			typePopupMenuPane.setTriangleLeft(typesBtn.getWidth());
			typePopupMenuPane.setVisibility(View.VISIBLE);
			FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) typePopupMenuPane
					.getLayoutParams();
			params.leftMargin = locate[0]
					- typePopupMenuPane.getUpTriangleView().getTriangleWidth()
					/ 2;
			typePopupMenuPane.setLayoutParams(params);
			typePopupMenuPane.setFocusable(true);
			typePopupMenuPane.setFocusableInTouchMode(true);
			typePopupMenuPane.setClickable(true);
			typePopupMenuPane.invalidate();
			typePopupMenuPane.requestLayout();
			typePopupMenuPane.bringToFront();
		}
	}

	/**
	 * 排序按钮的监听器
	 */
	private class SortBtnListener implements View.OnClickListener {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			typePopupMenuPane.hide();
			sortPopupMenuPane.setVisibility(View.INVISIBLE);
			int[] locate = new int[2];
			sortBtn.getLocationOnScreen(locate);
			FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) sortPopupMenuPane
					.getLayoutParams();
			int tmp = DisplayUtils.dm.widthPixels - locate[0]
					- sortBtn.getWidth();
			params.rightMargin = tmp / 2;
			sortPopupMenuPane.setLayoutParams(params);
			sortPopupMenuPane.measure(listframe.getWidth(),
					listframe.getHeight());
			sortPopupMenuPane.setTriangleLeft(sortPopupMenuPane
					.getMeasuredWidth()
					- sortBtn.getWidth()
					/ 2
					- params.rightMargin);
			sortPopupMenuPane.setVisibility(View.VISIBLE);
			sortPopupMenuPane.bringToFront();
			sortPopupMenuPane.setFocusable(true);
			sortPopupMenuPane.setFocusableInTouchMode(true);
			sortPopupMenuPane.setClickable(true);
			sortPopupMenuPane.requestLayout();
		}

	}

	/*
	 * 
	 * @see android.app.Activity#onDestroy() activity销毁时，把它从链表中去除
	 */
	@Override
	protected void onDestroy() {
		ActivityUtils.removeActivity(BoutiqueActivity.this);
		super.onDestroy();
	}

	/**
	 * 继承Handler,覆写handleMeseage方法
	 */
	@SuppressLint("HandlerLeak")
	private class BoutiqueHandler extends Handler {
		WeakReference<Activity> reference;

		static final int DONE_LOADING_LOCAL_DATA = 2;

		@SuppressLint("HandlerLeak")
		public BoutiqueHandler(Activity activity, Looper loop) {
			super(loop);
			reference = new WeakReference<Activity>(activity);
		}

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.arg1) {
			case MESSAGE_DATA_PREPARED:
				Log.i(TAG, "Handler handleMessage() called!");
				BoutiqueActivity activity = (BoutiqueActivity) reference.get();
				activity.runOnUiThread(new Runnable() {
					@Override
					public void run() {
						((BoutiqueActivity) reference.get()).adapter
								.notifyDataSetChanged();
					}
				});
				break;

			case DONE_LOADING_LOCAL_DATA:
				Log.i(TAG, "Handler handleMessage() called! ");
				BoutiqueActivity act = (BoutiqueActivity) reference.get();
				act.runOnUiThread(new Runnable() {
					@Override
					public void run() {
						((BoutiqueActivity) reference.get()).adapter
								.notifyDataSetChanged();
					}
				});
				break;
			default:
				break;
			}
		}
	}

	/**
	 * 实现Runnable接口，为排序菜单面板提供多线程支持
	 */
	private class BoutiqueSortRunnable implements Runnable {

		private int order = 0;

		/**
		 * 默认的排序方式
		 */
		public static final int ORDER_DEFAULT = 0;

		/**
		 * 按人气排序
		 */
		public static final int ORDER_BY_LIKED = 1;

		/**
		 * 按最新活动排序
		 */
		public static final int ORDER_BY_LATEST = 2;

		/**
		 * 按距离排序
		 */
		public static final int ORDER_BY_DISTANCE = 3;

		/**
		 * 根据折扣排序
		 */
		public static final int ORDER_BY_DISCOUNT = 4;

		/**
		 * 根据折扣排序的接口的实现类的实例
		 */
		private SortInterfaceImpls.SortByDiscountImpl sortByDiscountImpl = new SortInterfaceImpls.SortByDiscountImpl();

		/**
		 * 根据距离排序的接口的实现类的实例
		 */
		public SortInterfaceImpls.DistanceImpl distanceImpl = new SortInterfaceImpls.DistanceImpl();

		/**
		 * 根据最新活动排序
		 */
		public SortInterfaceImpls.LatestImpl latestImpl = new SortInterfaceImpls.LatestImpl();

		/**
		 * 根据人气排序
		 */
		// public SortInterfaceImpls.SortByLikeImpl likeImpl = new
		// SortByLikeImpl();

		@Override
		public void run() {
			Log.i(TAG, "BoutiqueSortRunnable run() called!");
			Message message = handler.obtainMessage();
			switch (order) {
			case ORDER_DEFAULT:
				break;

			case ORDER_BY_LIKED:
				// DiscountInfo.setComparator(likeImpl);
				// Collections.sort(list);
				// message.arg1 = MESSAGE_DATA_PREPARED;
				// handler.sendMessage(message);
				break;

			case ORDER_BY_LATEST:
//				Discount.setComparator(latestImpl);
				//Collections.sort(list);
				message.arg1 = MESSAGE_DATA_PREPARED;
				handler.sendMessage(message);
				break;

			case ORDER_BY_DISTANCE:
//				Discount.setComparator(distanceImpl);
//				Collections.sort(list);
				message.arg1 = MESSAGE_DATA_PREPARED;
				handler.sendMessage(message);
				break;

			case ORDER_BY_DISCOUNT:
//				Discount.setComparator(sortByDiscountImpl);
//				Collections.sort(list);
				message.arg1 = MESSAGE_DATA_PREPARED;
				handler.sendMessage(message);
				break;

			default:
				break;
			}
		}
	}

	/**
	 * 排序面板按钮的监听器
	 */
	private class SortPaneBtnsListener implements View.OnClickListener {
		@Override
		public void onClick(View v) {
			Log.i(TAG, "SortPaneBtnsListener");
			typePopupMenuPane.hide();
			sortPopupMenuPane.hide();
//			switch (v.getId()) {
//			case R.sort_menu_pane.latest_info:
//				sortRunnable.order = BoutiqueSortRunnable.ORDER_BY_LATEST;
//				handler.post(sortRunnable);
//				break;
//
//			case R.sort_menu_pane.best_discount:
//				sortRunnable.order = BoutiqueSortRunnable.ORDER_BY_DISCOUNT;
//				handler.post(sortRunnable);
//				break;
//
//			case R.sort_menu_pane.most_popular:
//				sortRunnable.order = BoutiqueSortRunnable.ORDER_BY_LIKED;
//				handler.post(sortRunnable);
//				break;
//
//			case R.sort_menu_pane.nearest:
//				sortRunnable.order = BoutiqueSortRunnable.ORDER_BY_DISTANCE;
//				handler.post(sortRunnable);
//				break;
//
//			default:
//				break;
//			}
		}

	}

	/**
	 * list view的item被点击的时候的listener
	 */
	private class BtqItemClickListener implements OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			Log.e(TAG, "item click!");
			Intent intent = new Intent(BoutiqueActivity.this,
					ShopDetailActivity.class);
			Log.i(TAG, list.get(arg2).toString());
			intent.putExtra("DiscountInfo", (Serializable)list.get(arg2));
			intent.putExtra("TAG", TAG);
			startActivity(intent);
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 1 && resultCode == RESULT_OK) {
			areaBtn.setText(application.getCurCity().name);
			handler.post(new Runnable() {
				@Override
				public void run() {
					reloadData();
					Message message = handler.obtainMessage();
					message.arg1 = BoutiqueHandler.DONE_LOADING_LOCAL_DATA;
					handler.sendMessage(message);
				}
			});
		}
	}
}
